﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Corel.Interop.VGCore;
using Microsoft.Win32;
using Svg;
using Svg.Transforms;
using ZXing;
using corel = Corel.Interop.VGCore;

namespace SampleDockerCS20221
{
    public partial class DockerUI : UserControl
    {
        private readonly corel.Application corelApp;
        private readonly Styles.StylesController stylesController;

        private readonly string d = "C:/temp/";
        public System.Windows.Media.Imaging.BitmapImage OpenedImage { get; set; }
        public string HistoryPath { get; set; } = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        public DockerUI(object app)
        {
            InitializeComponent();

            if (!Directory.Exists(d))
            {

                Directory.CreateDirectory(d);
            }
            try
            {
                this.corelApp = app as corel.Application;
                stylesController = new Styles.StylesController(this.Resources, this.corelApp);
            }
            catch
            {
                global::System.Windows.MessageBox.Show("VGCore Erro");
            }

        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            stylesController.LoadThemeFromPreference();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            BarcodeWriter<ZXing.Rendering.SvgRenderer.SvgImage> barcodeWriter = new BarcodeWriter<ZXing.Rendering.SvgRenderer.SvgImage>()
            {
                Renderer = new ZXing.Rendering.SvgRenderer(),
                Format = BarcodeFormat.QR_CODE,
                Options = new ZXing.QrCode.QrCodeEncodingOptions()
                {
                    Width = 300,
                    Height = 300,
                    Margin = 1,
                    CharacterSet = "utf-8"

                }

            };

            if (MessageTB.Text != "" && corelApp.ActiveLayer != null)
            {
                var svgimg = barcodeWriter.Write(MessageTB.Text);

                File.WriteAllText(d + "test.svg", svgimg.Content);

                //MessageBox.Show(d);
                corel.ImportFilter svgFilter = corelApp.ActiveLayer.ImportEx(d + "test.svg", corel.cdrFilter.cdrSVG);
                svgFilter.Finish();
            }
        }

        private void CreateShape(object sender, RoutedEventArgs e)
        {
            //VGCore.Shape sp;
            //double centerX = 0;
            //double centerY = 0;

            SvgDocument svgDocument = new SvgDocument();
            float gap = float.Parse(GapTB.Text);

            int row = int.Parse(RowTB.Text);
            int col = int.Parse(ColumnTB.Text);

            //circle
            float radius = float.Parse(RadiusTB.Text);
            float minRadius = float.Parse(MinRadiusTB.Text);

            //rectangle
            float rectWidth = float.Parse(WidthTB.Text);
            float minWidth = float.Parse(MinWidthTB.Text);

            if (corelApp.ActiveLayer == null)
            {
                MessageBox.MsgShow(corelApp, "请先打开一个文档。");
                return;
            }
            //else if (app.ActiveSelection.Shapes.Count <= 0)
            //{
            //    MessageBox.Show("请选择一个图形");
            //    return;
            //}
            //else
            //{
            //    //sp = app.ActiveSelection.Shapes[1];
            //    //centerX = app.ActiveSelection.PositionX;
            //    //centerY = app.ActiveSelection.PositionY;
            //}

            switch (ShapeCB.Text)
            {
                case "圆形":
                    for (int i = 0; i < row; i++)
                    {
                        for (int j = 0; j < col; j++)
                        {
                            SvgCircle svgEllipse = new SvgCircle()
                            {
                                CenterX = (2 * j + 1) * radius + gap * j,
                                CenterY = (2 * i + 1) * radius + gap * i,
                                Radius = radius - (radius - minRadius) / row * (row - i),
                            };

                            svgDocument.Children.Add(svgEllipse);
                        }
                    }
                    break;
                case "矩形":
                    for (int i = 0; i < row; i++)
                    {
                        for (int j = 0; j < col; j++)
                        {
                            SvgRectangle svgRect = new SvgRectangle()
                            {
                                X = (rectWidth + gap) * j,
                                Y = (rectWidth + gap) * i,
                                Width = rectWidth - (rectWidth - minWidth) / row * (row - i),
                                Height = rectWidth - (rectWidth - minWidth) / row * (row - i),
                            };

                            svgDocument.Children.Add(svgRect);
                        }
                    }
                    break;
                case "菱形":
                    for (int i = 0; i < row; i++)
                    {
                        for (int j = 0; j < col; j++)
                        {
                            SvgRectangle svgRect = new SvgRectangle()
                            {
                                X = (SvgUnit)((rectWidth * Math.Sqrt(2) + gap) * j),
                                Y = (SvgUnit)((rectWidth * Math.Sqrt(2) + gap) * i),
                                Width = rectWidth - (rectWidth - minWidth) / row * (row - i),
                                Height = rectWidth - (rectWidth - minWidth) / row * (row - i),
                            };
                            SvgRotate svgRotate = new SvgRotate(45)
                            {
                                CenterX = svgRect.X + svgRect.Width / 2,
                                CenterY = svgRect.Y + svgRect.Height / 2
                            };
                            if (svgRect.Transforms == null)
                            {
                                svgRect.Transforms = new SvgTransformCollection();
                            }
                            svgRect.Transforms.Add(svgRotate);
                            svgDocument.Children.Add(svgRect);
                        }
                    }
                    break;
                default:
                    break;
            }

            svgDocument.Write(d + "test1.svg");

            corel.ImportFilter svgFilter = corelApp.ActiveLayer.ImportEx(d + "test1.svg", corel.cdrFilter.cdrSVG);
            svgFilter.Finish();


            //app.ActiveSelection.SetPosition(centerX, centerY);
            //app.ActiveSelection.AddToPowerClip(sp);

        }

        private void OpenImage(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog
            {
                Filter = "Image Files|*.jpg;*.png;*.jpeg",
                Title = "选择图片",
                InitialDirectory = HistoryPath,
                Multiselect = false,
                FilterIndex = 0
            };
            if (fileDialog.ShowDialog() == true)
            {
                ImagePathTB.Text = fileDialog.FileName;
                OpenedImage = new System.Windows.Media.Imaging.BitmapImage(new Uri(fileDialog.FileName));
                OpImage.Source = OpenedImage;
                HistoryPath = System.IO.Path.GetDirectoryName(fileDialog.FileName);
            }
        }

        private void CreateImageShape(object sender, RoutedEventArgs e)
        {
            if (OpenedImage == null)
            {
                MessageBox.MsgShow(corelApp, "请先加载图片！");
                return;
            }

            CreateShape(OpenedImage, GrayCB.IsChecked.Value, RevertCB.IsChecked.Value, OpImage);

            ImportFilter svgFilter = corelApp.ActiveLayer.ImportEx(d + "output.svg", cdrFilter.cdrSVG);
            svgFilter.Finish();
        }

        public void CreateShape(System.Windows.Media.Imaging.BitmapImage bitmap, bool isGray, bool isRevert, System.Windows.Controls.Image image)
        {
            int width;
            int height;
            byte[] Pixels;

            //原图
            WriteableBitmap originalBitmap = new WriteableBitmap(bitmap);

            image.Source = originalBitmap;
            // 将图片转换为灰度图
            WriteableBitmap grayBitmap = RGB2Gray(bitmap);

            if (isGray == true)
            {
                // 将图片转换为灰度图
                image.Source = grayBitmap;

                // 获取图片宽高
                width = grayBitmap.PixelWidth;
                height = grayBitmap.PixelHeight;

                // 获取灰度图像素数据
                Pixels = new byte[width * height];
            }
            else
            {
                // 获取图片宽高
                width = originalBitmap.PixelWidth;
                height = originalBitmap.PixelHeight;
                Pixels = new byte[width * height * 4];
            }

            // 固定分块的行列数
            int rows = int.Parse(BlocksNumsTB.Text);
            int cols = int.Parse(BlocksNumsTB.Text);

            // 计算每个分块的宽高
            float blockWidth = (float)width / cols;
            float blockHeight = (float)height / rows;

            // 创建 SVG 文档并设置宽高
            SvgDocument svgDocument = new SvgDocument
            {
                Width = new SvgUnit(width),
                Height = new SvgUnit(height)
            };

            if (isGray == true)
            {

                int stride = width;
                // 将灰度图像素数据复制到字节数组中
                grayBitmap.CopyPixels(Pixels, stride, 0);
                // 遍历每个分块，计算平均灰度值并生成圆形
                for (int row = 0; row < rows; row++)
                {
                    for (int col = 0; col < cols; col++)
                    {
                        // 计算分块的起始位置
                        float startX = col * blockWidth;
                        float startY = row * blockHeight;

                        //// 计算分块的实际宽高（处理最后一列和最后一行）
                        //int actualBlockWidth = (col == cols - 1) ? (width - startX) : blockWidth;
                        //int actualBlockHeight = (row == rows - 1) ? (height - startY) : blockHeight;

                        // 计算分块的平均灰度值
                        int sumGray = 0;
                        int pixelCount = 0;
                        for (int y = (int)startY; y < startY + blockHeight && y < height; y++)
                        {
                            for (int x = (int)startX; x < startX + blockWidth && x < width; x++)
                            {
                                sumGray += Pixels[y * width + x];
                                pixelCount++;
                            }
                        }
                        int avgGray = sumGray / pixelCount;

                        // 将灰度值映射到圆的半径
                        float maxRadius = Math.Min(blockWidth, blockHeight) / 2f;
                        float radius = maxRadius * (1 - avgGray / 255f);
                        if (isRevert)
                        {
                            radius = maxRadius * (avgGray / 255f);
                        }


                        // 创建圆形并添加到 SVG 文档
                        SvgCircle circle = new SvgCircle
                        {
                            CenterX = (startX + blockWidth / 2),
                            CenterY = startY + blockHeight / 2,
                            Radius = radius
                        };
                        svgDocument.Children.Add(circle);
                    }
                }
            }
            else
            {

                int stride = width * 4;
                // 将原图像素数据复制到字节数组中
                originalBitmap.CopyPixels(Pixels, stride, 0);
                // 遍历每个分块，计算平均颜色并生成图形
                for (int row = 0; row < rows; row++)
                {
                    for (int col = 0; col < cols; col++)
                    {
                        // 计算分块的起始位置
                        float startX = col * blockWidth;
                        float startY = row * blockHeight;

                        //// 计算分块的实际宽高（处理最后一列和最后一行）
                        //int actualBlockWidth = (col == cols - 1) ? (width - startX) : blockWidth;
                        //int actualBlockHeight = (row == rows - 1) ? (height - startY) : blockHeight;

                        // 计算分块的平均颜色
                        int sumR = 0, sumG = 0, sumB = 0;
                        int pixelCount = 0;
                        for (int y = (int)startY; y < startY + blockWidth && y < height; y++)
                        {
                            for (int x = (int)startX; x < startX + blockHeight && x < width; x++)
                            {
                                int pixelIndex = (y * width + x) * 4;
                                byte b = Pixels[pixelIndex];
                                byte g = Pixels[pixelIndex + 1];
                                byte r = Pixels[pixelIndex + 2];

                                sumR += r;
                                sumG += g;
                                sumB += b;
                                pixelCount++;
                            }
                        }

                        // 计算平均颜色
                        byte avgR = (byte)(sumR / pixelCount);
                        byte avgG = (byte)(sumG / pixelCount);
                        byte avgB = (byte)(sumB / pixelCount);

                        // 创建图形（例如圆形）并设置填充颜色
                        SvgCircle circle = new SvgCircle
                        {
                            CenterX = startX + blockWidth / 2,
                            CenterY = startY + blockHeight / 2,
                            Radius = Math.Min(blockWidth, blockHeight) / 2f,
                            Fill = new SvgColourServer(System.Drawing.Color.FromArgb(avgR, avgG, avgB))
                        };

                        // 添加图形到 SVG 文档
                        svgDocument.Children.Add(circle);
                    }
                }
            }



            // 保存 SVG 文件
            svgDocument.Write(d + "output.svg");

        }


        private WriteableBitmap RGB2Gray(System.Windows.Media.Imaging.BitmapImage bitmap)
        {
            int width = bitmap.PixelWidth;
            int height = bitmap.PixelHeight;
            WriteableBitmap grayBitmap = new WriteableBitmap(width, height, bitmap.DpiX, bitmap.DpiY, PixelFormats.Gray8, null);

            // Create a byte array to hold pixel data  
            byte[] pixels = new byte[width * height * 4];
            bitmap.CopyPixels(pixels, width * 4, 0);

            byte[] grayPixels = new byte[width * height];

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    int pixelIndex = (y * width + x) * 4;
                    byte r = pixels[pixelIndex + 2];
                    byte g = pixels[pixelIndex + 1];
                    byte b = pixels[pixelIndex];
                    byte grayValue = (byte)((r + g + b) / 3);
                    grayPixels[y * width + x] = grayValue;
                }
            }

            grayBitmap.WritePixels(new Int32Rect(0, 0, width, height), grayPixels, width, 0);
            return grayBitmap;
        }

        private void CreateImageShapeEx(object sender, RoutedEventArgs e)
        {
            if (corelApp.ActiveSelection.Shapes.Count == 1)
            {
                corel.Shape sp = corelApp.ActiveSelection.Shapes.First;

                corelApp.ActiveDocument.Unit = cdrUnit.cdrMillimeter;
                double posX = sp.PositionX;
                double posY = sp.PositionY;
                double width = sp.SizeWidth;
                double height = sp.SizeHeight;


                //MessageBox.MsgShow(corelApp, sp.OriginalHeight.ToString());
                ExportFilter ef = corelApp.ActiveDocument.ExportBitmap(d + "export.jpg", cdrFilter.cdrJPEG, cdrExportRange.cdrSelection, cdrImageType.cdrRGBColorImage, (int)(width), (int)(height), 100, 100);

                ef.Finish();
                if (File.Exists(d + "export.jpg"))
                {
                    //MessageBox.Show("导出成功");
                    OpenedImage = new System.Windows.Media.Imaging.BitmapImage(new Uri(d + "export.jpg"));
                    CreateShape(OpenedImage, GrayCB.IsChecked.Value, RevertCB.IsChecked.Value, OpImage);


                    ImportFilter impf = corelApp.ActiveLayer.ImportEx(d + "output.svg", cdrFilter.cdrSVG);
                    impf.Finish();
                    corelApp.ActiveSelection.SetSize(width, height);
                    corelApp.ActiveSelection.SetPosition(posX, posY);
                }

            }
            else { MessageBox.MsgShow(corelApp, "仅选择一个图形"); }
        }
    }
}
